﻿using Server.MessageModule.Message;
using Server.MessageModule.MessageProcessor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Server.MessageModule
{
    public class MessageDispatcher : IMessageDispatcher
    {
        private Dictionary<string, IMessageProcessor> _target;

        public MessageDispatcher()
        {
            _target = new Dictionary<string, IMessageProcessor>();
        }

        public void addMessageProcessor(IMessageProcessor processor)
        {
            if (processor == null)
                return;
            if (_target.ContainsKey(processor.getTypeProcessor()))
                _target.Remove(processor.getTypeProcessor());

            _target.Add(processor.getTypeProcessor(), processor);
            processor.setMessageDispatcher(this);
        }

        public void dispatchMessage(INetworkMessage msg)
        {
            if (msg == null)
                return;
            foreach (var item in _target)
            {
                item.Value.onReceiptMessage(msg);
            }
        }

        public IMessageProcessor getProcessor(string type)
        {
            if (_target.ContainsKey(type))
                return _target[type];
            else
                return null;
        }
    }
}
